<?php

namespace app\api\model\hotel;


use app\admin\model\Crontab;
use app\admin\model\hotel\HotelRoomType;
use app\api\model\hotel\HotelRoom as HotelRoomModel;
use app\api\model\UserCoupon;
use app\common\model\hotel\Hotel as HotelModel;
use app\common\model\hotel\Order as OrderModel;
use app\common\model\User;
use app\common\model\User as UserModel;
use think\Db;
use think\Model;



class OrderCreate extends Model
{
    // 订单创建
    const ORDER_CREATE = 0;

    // 订单待入住
    const ORDER_WAIT_CHECKIN = 1;

    //已完成
    const ORDER_COMPLETE = 10;

    //已取消
    const ORDER_CLOSE = -1;

    public $order_status = [
        self::ORDER_CREATE           => [
            'status'          => self::ORDER_CREATE,
            'name'            => '待支付',
        ],
        self::ORDER_WAIT_CHECKIN           => [
            'status'          => self::ORDER_WAIT_CHECKIN,
            'name'            => '待入住',
        ],
        self::ORDER_COMPLETE           => [
            'status'          => self::ORDER_COMPLETE,
            'name'            => '已完成',
        ],
        self::ORDER_CLOSE           => [
            'status'          => self::ORDER_CLOSE,
            'name'            => '已取消',
        ],
    ];


    public function ordercreate($data)
    {
        if (empty($data['hotel_id'])){
            throw new \Exception('缺少必传酒店id');
        }
        if (empty($data['checkin_date'])){
            throw new \Exception('请传入入住日期');
        }
        if (empty($data['checkout_date'])){
            throw new \Exception('请传入离店日期');
        }
        if (empty($data['guest_name'])){
            throw new \Exception('请输入姓名');
        }
        if (empty($data['phone'])){
            throw new \Exception('请输入联系电话');
        }

        //$hotel_id = $data['hotel_id'];
        //$checkin_date = $data['checkin_date'];
        //$checkout_date = $data['checkout_date'];
        $coupon_id = $data['coupon_id'];

        $calculate_data = $this->calculate($data);

        if (isset($calculate_data[ 'code' ]) && $calculate_data[ 'code' ] < 0)
            return $calculate_data;

        Db::startTrans();

        try {
            $order_model = new HotelThirdOrder();

            $order_data = [
                'hotel_id'=>$data['hotel_id'],
                'user_id'=>$data['user_id'],
                'order_no'=>order_no(),
                'checkin_date'=>$data['checkin_date'],
                'checkout_date'=>$data['checkout_date'],
                'guest_name'=>$data['guest_name'],
                'phone'=>$data['phone'],
                'remark'=>$data['remark'],
                'room_num'=>$data['room_num'],
                'room_type_code'=>$data['room_type_code'],
                'room_type_name'=>$data['room_type_name'],
                'day'=>$calculate_data['days'],
                'order_status_name'=>'待支付',
                'room_money'=>$calculate_data['room_money'],
                'order_money'=>$calculate_data['order_money'],
                'pay_money'=>$calculate_data['pay_money'],
                'coupon_id'=>$coupon_id,
                'coupon_money'=>$calculate_data['coupon_money'],
                'score_money'=>$calculate_data['score_money'],
                'use_score'=>$calculate_data['use_score'],
                'award_score'=>$calculate_data['award_score'],
                'discount_money'=>$calculate_data['discount_money'],
            ];

            $res = $order_model->save($order_data);

            if ($res){
                $order_id = $order_model->order_id;
                //扣积分
                if ($order_model->use_score<0){
                    User::score($order_model->use_score,$order_model->user_id,'积分抵扣,订单号:'.$order_model->order_no);
                }

                //修改优惠券状态
                if ($order_model->coupon_id){
                    $UserCoupon = UserCoupon::get($order_model->coupon_id);
                    $UserCoupon->is_used = 2;
                    $UserCoupon->use_time = time();
                    $UserCoupon->order_id = $order_id;
                    $UserCoupon->save();
                }

                //定时任务关闭订单
                $cron = new Crontab();
                $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;
                $end_time_timestamp = time()+$auto_close;
                $cron_data = [
                    'type'=>'url',
                    'title'=>'关闭订单,订单id:'.$order_id,
                    'content'=>request()->domain().'/api/hotelorder/cancel?order_id='.$order_id,
                    'schedule'=>schedule($end_time_timestamp),
                    'maximums'=>1,
                    'begintime'=>time(),
                    'endtime'=>$end_time_timestamp,
                    'status'=>'normal'
                ];
                $cron->save($cron_data);
                Db::commit();
                return $order_model->order_no;
            }  else {
                Db::rollback();
                throw new \Exception('提交失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage().'_'.$e->getLine());
        }

    }


    public function calculate($data)
    {
        if (empty($data['hotel_id'])){
            throw new \Exception('缺少必传酒店id');
        }
        if (empty($data['checkin_date'])){
            throw new \Exception('请传入入住日期');
        }
        if (empty($data['checkout_date'])){
            throw new \Exception('请传入离店日期');
        }

        $hotel = new OrderModel();

        /*$check_res = $hotel->order_check($data);
        if ($check_res['code']==0){
            throw new \Exception($check_res['msg']);
        } else {

        }*/

        $hotel_id = $data['hotel_id'];
        $room_type_name = $data['room_type_name'];
        $room_num = $data['room_num'];
        $user_id = $data['user_id'];
        $checkin_date = $data['checkin_date'];
        $checkout_date = $data['checkout_date'];
        $use_score = $data['use_score'];
        $room_type_code = $data['room_type_code'];

        //账户信息
        $user_info = User::where(['id'=>$user_id])->field('id,nickname,mobile,avatar,score,money,level')->find();

        if ($use_score>$user_info['score']){
            throw new \Exception('积分不足');
        }

        $order_money = 0;//订单金额
        $pay_money = 0;//付款金额
        $coupon_money = 0;//优惠券优惠金额
        //$use_score = 0;//抵扣使用的积分
        $score_money = 0;//积分抵扣金额
        $award_score = 0;//奖励积分
        $room_money = 0;//房间金额
        $discount_money = 0;//房间折扣优惠金额
        $max_use_score = 0;//最高可使用的抵现积分

        $userCoupon = null;

        $days = getDaysBetweenTwoTimestamps($checkin_date,$checkout_date);

        $room_type = HotelRoomType::get(['room_type_name'=>$room_type_name]);

        $room_model = new HotelRoomModel;
        $member_price = $room_model->getRoomPrice($room_type['id'],$user_id);
        $discount_price = $room_model->getRoomDiscountPrice($room_type['id']);

        $discount_price = bcmul($room_num,$discount_price['member_price'],2);//折扣价
        $original_price = bcmul($room_num,$room_type['price'],2);//原价
        if ($member_price['member_price']){
            $room_price = bcmul($room_num,$member_price['member_price'],2);
        } else {
            $room_price = bcmul($room_num,$room_type['price'],2);
        }
        $discount_room_money =  bcmul($days,$discount_price,2);

        $original_room_price = bcmul($days,$original_price,2);

        $room_money = bcmul($days,$room_price,2);

        $discount_money = bcsub($original_room_price,$room_money,2);
        $order_money = $room_money;
        $pay_money = $room_money;
        //优惠券列表
        $coupon_list = UserCoupon::myGoodsCoupon($user_id,$data['hotel_id'],$order_money);

        //校验领取和是否可使用
        if ($data['coupon_id']) {
            $userCouponModel = new UserCoupon();
            $userCoupon = $userCouponModel->checkUserOrUse($data['coupon_id'], $data['user_id']);
        }

        if (!empty($userCoupon)) {
            //校验优惠券
            $couponModel = new \app\api\model\Coupon();
            $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
                ->checkCoupon()
                ->checkOpen()
                ->checkUseTime($userCoupon['createtime']);

            $coupon_money = $coupon->doBuy($order_money);
            $coupon_money = $coupon_money[1];
        }

        if ($coupon_money>0){
            $pay_money = bcsub($pay_money,$coupon_money,2);
        }

        $use_score_rate = \app\common\model\Config::get(['name'=>'use_score_rate'])->value/100;
        //$max_use_score = round($room_money,$use_score_rate);
        $max_use_score = round($order_money * $use_score_rate);
        if ($use_score>0){
            $cash_rate = \app\common\model\Config::get(['name'=>'cash_rate'])->value;
            $score_money = round(( $use_score * ( 1 / $cash_rate ) ), 2);
            if ($score_money > $order_money) {
                $score_money = $order_money;
            }
            $pay_money = bcsub($pay_money,$score_money,2);
        }

        if ($pay_money>0){
            $return_point_rate = \app\common\model\Config::get(['name'=>'return_point_rate'])->value/100;
            $award_score =  round($pay_money * $return_point_rate);
        }
        $hotel = new HotelModel();

        $room_type_info = $hotel->room_type_detail($hotel_id,$room_type_code);
        $hotel_info = $hotel->get_hotel_detail($hotel_id);
        return [
            'user_info'=>$user_info,
            'coupon_list'=>$coupon_list,
            'days'=>$days,
            'order_money'=>$order_money,
            'pay_money'=>$pay_money,
            'discount_room_money'=>$discount_room_money,
            'room_money'=>$room_money,
            'coupon_money'=>$coupon_money,
            'score_money'=>$score_money,
            'use_score'=>$use_score,
            'award_score'=>$award_score,
            'max_use_score'=>$max_use_score,
            'discount_money'=>$discount_money,
            'room_num'=>$room_num,
            'room_type_info'=>$room_type_info,
            'hotel_info'=>$hotel_info,
        ];
    }




}
